package com.deyou.fragment;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.deyou.DeYouApplication;
import com.deyou.R;
import com.deyou.adapter.MsgListAdapter;
import com.deyou.adapter.NotifyListAdapter;
import com.deyou.base.BaseFragment;
import com.deyou.chatting.ChatActivity;
import com.deyou.chatting.utils.HandleResponseCode;
import com.deyou.chatting.utils.SortConvList;
import com.deyou.event.Event;
import com.deyou.model.MsgBean;
import com.deyou.util.AndroidUtils;
import com.deyou.util.Logger;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import cn.jpush.im.android.api.JMessageClient;
import cn.jpush.im.android.api.callback.GetAvatarBitmapCallback;
import cn.jpush.im.android.api.enums.ConversationType;
import cn.jpush.im.android.api.event.ConversationRefreshEvent;
import cn.jpush.im.android.api.event.MessageEvent;
import cn.jpush.im.android.api.event.OfflineMessageEvent;
import cn.jpush.im.android.api.model.Conversation;
import cn.jpush.im.android.api.model.Message;
import cn.jpush.im.android.api.model.UserInfo;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * to handle interaction events.
 * Use the {@link MsgCenterFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class MsgCenterFragment extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener, BaseQuickAdapter.OnItemClickListener {
    @BindView(R.id.tv_tab_one)
    TextView tvTabOne;
    @BindView(R.id.tab_line_one)
    View tabLineOne;
    @BindView(R.id.tab_one_layout)
    RelativeLayout tabOneLayout;
    @BindView(R.id.tv_tab_two)
    TextView tvTabTwo;
    @BindView(R.id.tab_line_two)
    View tabLineTwo;
    @BindView(R.id.tab_two_layout)
    RelativeLayout tabTwoLayout;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.notify_recyclerView)
    RecyclerView notifyRecyclerView;
    @BindView(R.id.refreshLayout)
    SwipeRefreshLayout refreshLayout;

    Unbinder unbinder;
    private Context mContext;
    private MsgListAdapter mMsgAdapter;
    private NotifyListAdapter mNofityAdapter;
    private int msgType = 1;
    private List<MsgBean> notifyList = new ArrayList<>();
    private List<Conversation> msgList = new ArrayList<>();
    private static final int REFRESH_CONVERSATION_LIST = 0x3000;
    private static final int ROAM_COMPLETED = 0x3002;
//    private HandlerThread mThread;
//    private BackgroundHandler mBackgroundHandler;

    public MsgCenterFragment() {
    }

    MsgListAdapter.OnMsgItemClickerListener msgItemClick = new MsgListAdapter.OnMsgItemClickerListener() {
        @Override
        public void msgItemClick(Conversation conversation) {
            Bundle bundle = new Bundle();
            if (null == conversation) {
                return;
            }
            if (null != conversation.getTargetInfo())
                bundle.putString(DeYouApplication.TARGET_ID, ((UserInfo) conversation.getTargetInfo()).getUserName());
            else
                bundle.putString(DeYouApplication.TARGET_ID, "DeYou_332003197");
            bundle.putString(DeYouApplication.TARGET_APP_KEY, conversation.getTargetAppKey());
            bundle.putString(DeYouApplication.DRAFT, mMsgAdapter.getDraft(conversation.getId()));
            bundle.putString(DeYouApplication.CONV_TITLE, ((UserInfo) conversation.getTargetInfo()).getUserName());
            AndroidUtils.startNextActivity(getActivity(), ChatActivity.class, bundle, false);
        }
    };

    public static MsgCenterFragment newInstance(String param1, String param2) {
        MsgCenterFragment fragment = new MsgCenterFragment();
        return fragment;
    }

    @Override
    public void onAttach(Context context) {
        this.mContext = context;
        EventBus.getDefault().register(this);
        JMessageClient.registerEventReceiver(this);
        super.onAttach(context);
    }

    @Override
    protected View initView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_msg_center, container, false);
        unbinder = ButterKnife.bind(this, view);
        return view;
    }

    @Override
    protected void initData() {
//        mThread = new HandlerThread("Work on MainActivity");
//        mThread.start();
//        mBackgroundHandler = new BackgroundHandler(mThread.getLooper());
        msgType = 1;
        tvTabOne.setText("聊天");
        tvTabTwo.setText("提醒");

        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        recyclerView.addItemDecoration(new DividerItemDecoration(mContext, DividerItemDecoration.HORIZONTAL));
        mMsgAdapter = new MsgListAdapter(mContext);
        recyclerView.setAdapter(mMsgAdapter);
        mMsgAdapter.setOnMsgItemClick(msgItemClick);

        notifyRecyclerView.setItemAnimator(new DefaultItemAnimator());
        notifyRecyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        notifyRecyclerView.addItemDecoration(new DividerItemDecoration(mContext, DividerItemDecoration.HORIZONTAL));
        mNofityAdapter = new NotifyListAdapter(mContext);
        mNofityAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        mNofityAdapter.isFirstOnly(true);
        mNofityAdapter.setOnItemClickListener(this);
        notifyRecyclerView.setAdapter(mNofityAdapter);

        refreshLayout.setColorSchemeColors(Color.RED, Color.BLUE, Color.GREEN);
        refreshLayout.setOnRefreshListener(this);

        setRefreshing(true);
        onRefresh();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
        JMessageClient.unRegisterEventReceiver(this);
        EventBus.getDefault().unregister(this);
//        mBackgroundHandler.removeCallbacksAndMessages(null);
//        mThread.getLooper().quit();
    }

    @OnClick({R.id.tab_one_layout, R.id.tab_two_layout})
    public void onViewClicked(View view) {
        tabLineOne.setVisibility(View.GONE);
        tvTabOne.setTextColor(getResources().getColor(R.color.color_272424));
        tabLineTwo.setVisibility(View.GONE);
        tvTabTwo.setTextColor(getResources().getColor(R.color.color_272424));
        switch (view.getId()) {
            case R.id.tab_one_layout:
                tabLineOne.setVisibility(View.VISIBLE);
                tvTabOne.setTextColor(getResources().getColor(R.color.color_FF832D));
                msgType = 1;
                onRefresh();
                break;
            case R.id.tab_two_layout:
                tabLineTwo.setVisibility(View.VISIBLE);
                tvTabTwo.setTextColor(getResources().getColor(R.color.color_FF832D));
                msgType = 2;
                onRefresh();
                break;
        }
    }

    public void setRefreshing(final boolean refreshing) {
        refreshLayout.post(new Runnable() {
            @Override
            public void run() {
                refreshLayout.setRefreshing(refreshing);
            }
        });
    }

    @Override
    public void onRefresh() {
        setRefreshing(false);
        if (msgType == 1) {
            recyclerView.setVisibility(View.VISIBLE);
            notifyRecyclerView.setVisibility(View.GONE);
            mMsgAdapter.setMsgType(msgType);
            msgList = JMessageClient.getConversationList();
            //对会话列表进行时间排序
            if (msgList.size() > 1) {
                SortConvList sortList = new SortConvList();
                Collections.sort(msgList, sortList);
            }
            mMsgAdapter.setmDatas(msgList);
        } else if (msgType == 2) {
            if (null != notifyList)
                notifyList.clear();
            recyclerView.setVisibility(View.GONE);
            notifyRecyclerView.setVisibility(View.VISIBLE);
            for (int i = 0; i < 3; i++) {
                MsgBean msg = new MsgBean();
                msg.resourceId = i + "";
                notifyList.add(msg);
            }
            mNofityAdapter.setMsgType(msgType);
            mNofityAdapter.setNewData(notifyList);
        }

    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        // 提醒消息列表专用
//        Bundle bundle = new Bundle();
//        bundle.putString(DeYouApplication.TARGET_ID, "DeYou_332003197");
//        bundle.putString(DeYouApplication.TARGET_APP_KEY, "544c5c3a1f26ec4ec01f132c");
//        bundle.putString(DeYouApplication.DRAFT, "");
//        bundle.putString(DeYouApplication.CONV_TITLE, "DeYou_332003197");
//        AndroidUtils.startNextActivity(getActivity(), ChatActivity.class, bundle, false);
    }

    /**
     * 在会话列表中接收在线消息
     *
     * @param event 消息事件
     */
    public void onEvent(MessageEvent event) {
        Message msg = event.getMessage();
        Logger.d(Logger.LOGTAG, "收到消息：msg = " + msg.toString());
        ConversationType convType = msg.getTargetType();
        final UserInfo userInfo = (UserInfo) msg.getTargetInfo();
        final String targetId = userInfo.getUserName();
        final Conversation conv = JMessageClient.getSingleConversation(targetId, userInfo.getAppKey());
        if (conv != null) {
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    //如果设置了头像
                    if (!TextUtils.isEmpty(userInfo.getAvatar())) {
                        //如果本地不存在头像
                        userInfo.getAvatarBitmap(new GetAvatarBitmapCallback() {
                            @Override
                            public void gotResult(int status, String desc, Bitmap bitmap) {
                                if (status == 0) {
                                    mMsgAdapter.notifyDataSetChanged();
                                } else {
                                    HandleResponseCode.onHandle(mContext, status, false);
                                }
                            }
                        });
                    }
                }
            });
            handler.sendMessage(handler.obtainMessage(REFRESH_CONVERSATION_LIST, conv));
        }
    }

    /**
     * 接收离线消息
     *
     * @param event 离线消息事件
     */
    public void onEvent(OfflineMessageEvent event) {
        Conversation conv = event.getConversation();
        handler.sendMessage(handler.obtainMessage(REFRESH_CONVERSATION_LIST, conv));
    }

    /**
     * 消息漫游完成事件
     *
     * @param event 漫游完成后， 刷新会话事件
     */
    public void onEvent(ConversationRefreshEvent event) {
        Conversation conv = event.getConversation();
        handler.sendMessage(handler.obtainMessage(REFRESH_CONVERSATION_LIST, conv));
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void createConv(Event event) {
        switch (event.getType()) {
            case createConversation:
                Conversation conv = event.getConversation();
                if (conv != null) {
                    mMsgAdapter.addNewConversation(conv);
                }
                break;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(Event event) {
        switch (event.getType()) {
            case createConversation:
                Conversation conv = event.getConversation();
                if (conv != null) {
                    mMsgAdapter.addNewConversation(conv);
                }
                break;
            case deleteConversation:
                conv = event.getConversation();
                if (null != conv) {
                    mMsgAdapter.deleteConversation(conv);
                }
                break;
            //收到保存为草稿事件
            case draft:
                conv = event.getConversation();
                String draft = event.getDraft();
                //如果草稿内容不为空，保存，并且置顶该会话
                if (!TextUtils.isEmpty(draft)) {
                    mMsgAdapter.putDraftToMap(conv, draft);
                    mMsgAdapter.setToTop(conv);
                    //否则删除
                } else {
                    mMsgAdapter.delDraftFromMap(conv);
                }
                break;
            case addFriend:
                break;
        }
    }

    Handler handler = new Handler(){
        @Override
        public void handleMessage(android.os.Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case REFRESH_CONVERSATION_LIST:
                    Conversation conv = (Conversation) msg.obj;
                    mMsgAdapter.setToTop(conv);
                    break;
                case ROAM_COMPLETED:
                    conv = (Conversation) msg.obj;
                    mMsgAdapter.addAndSort(conv);
                    break;
            }
        }
    };
}
